import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:hixing_app/widgets/toast/toast.dart';
import 'dart:math' as math;

import 'widget/scan_device_item.dart';

class ScanBle extends StatefulWidget {
  @override
  _ScanBleState createState() => _ScanBleState();
}

class _ScanBleState extends State<ScanBle> {
  BluetoothDevice? _currentConnectDevice;

  List<BluetoothDevice> _systemDevices = [];
  List<ScanResult> _scanResults = [];
  List<ScanResult> _filterRes = [];
  bool _isScanning = false;
  late StreamSubscription<List<ScanResult>> _scanResultsSubscription;
  late StreamSubscription<bool> _isScanningSubscription;
  RegExp laserExp = RegExp("L.{2}-");

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
      _scanResults = results;

      if (mounted) {
        setState(() {});
      }
    }, onError: (e) {
      // Snackbar.show(ABC.b, prettyException("Scan Error:", e), success: false);
    });

    _isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
      _isScanning = state;
      if (!state) {
        // 扫描结束 过滤打印机
        print("扫描结束============");
        List<ScanResult> _arr = [];
        _scanResults.forEach((element) {
          bool isLaser = laserExp.hasMatch(element.advertisementData.advName);
          bool isLaserStart =
              element.advertisementData.advName.startsWith("LaserPecker");
          if (isLaser || isLaserStart) {
            print("${element.advertisementData.advName}");
            _arr.add(element);
          }
        });
        _arr.sort((a, b) => b.rssi.compareTo(a.rssi));
        setState(() {
          _filterRes = _arr;
        });
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _scanResultsSubscription.cancel();
    _isScanningSubscription.cancel();
    super.dispose();
  }

  Future onScanPressed() async {
    try {
      _systemDevices = await FlutterBluePlus.systemDevices;
      // print("当前的设备信息：${_systemDevices}");
    } catch (e) {
      // Snackbar.show(ABC.b, prettyException("System Devices Error:", e), success: false);
    }
    try {
      await FlutterBluePlus.startScan(timeout: const Duration(seconds: 5));
    } catch (e) {
      // Snackbar.show(ABC.b, prettyException("Start Scan Error:", e), success: false);
    }
    if (mounted) {
      setState(() {});
    }
  }

  Future onStopPressed() async {
    try {
      FlutterBluePlus.stopScan();
    } catch (e) {
      // Snackbar.show(ABC.b, prettyException("Stop Scan Error:", e), success: false);
    }
  }

  // void onConnectPressed(BluetoothDevice device) {}

  Future onRefresh() {
    if (_isScanning == false) {
      FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));
    }
    if (mounted) {
      setState(() {});
    }
    return Future.delayed(Duration(milliseconds: 500));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "扫描设备",
        ),
      ),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                onScanPressed();
              },
              child: Text("开始扫描")),
          ElevatedButton(
              onPressed: () {
                FlutterBluePlus.connectedDevices.forEach((element) {
                  element.disconnect();
                });
              },
              child: Text("关闭所有设备")),
          _buildData(),
        ],
      ),
      floatingActionButton: buildScanButton(context),
    );
  }

  Widget _buildData() {
    return Expanded(
      child: ListView.builder(
        itemCount: _filterRes.length,
        itemBuilder: (ctx, index) {
          var itemData = _filterRes[index];
          return ScanDeviceItem(
            itemData: _filterRes[index],
            onTap: (isConnected) async {
              print("${itemData}");
              if (!isConnected) {
                if (_currentConnectDevice == itemData.device) return;
                try {
                  AppToast.showLoading();
                  await itemData.device.connect();

                  _currentConnectDevice?.disconnect();
                  // 未连接，点击连
                  _currentConnectDevice = itemData.device;

                  AppToast.closeAllLoading();
                  AppToast.showText("蓝牙连接成功");
                  int _mtu = await _currentConnectDevice!.requestMtu(512);
                  print("当前的mtu值为:${_mtu}");
                  setState(() {});
                } catch (e) {
                  AppToast.closeAllLoading();
                  // AppToast.showText("蓝牙连接失败：$e");
                }
              } else {
                // 已连接 点击断开
                itemData.device.disconnect();
                _currentConnectDevice = null;
              }
              if (mounted) {
                setState(() {});
              }
            },
          );
        },
      ),
    );
  }

  Widget buildScanButton(BuildContext context) {
    if (FlutterBluePlus.isScanningNow) {
      return FloatingActionButton(
        child: const Icon(Icons.stop),
        onPressed: onStopPressed,
        backgroundColor: Colors.red,
      );
    } else {
      return FloatingActionButton(
          child: const Text("SCAN"), onPressed: onScanPressed);
    }
  }
}
